package com.zbs.framework.swagger.scan;

import com.zbs.framework.swagger.constants.SwaggerApiConstant;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

import java.util.Objects;

public class ApiScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    ResourceLoader resourceLoader;



    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;

    }


    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //获取所有注解的属性和值
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(ApiScan.class.getName()));
        //获取到basePackage的值
        String[] basePackages = Objects.requireNonNull(annoAttrs).getStringArray("basePackage");
        //如果没有设置basePackage 扫描路径,就扫描对应包下面的值
        if(basePackages.length == 0){
            basePackages = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName()};
        }
        boolean enableCheckParams = Objects.requireNonNull(annoAttrs).getBoolean(SwaggerApiConstant.enableCheckParams);
        boolean enableRequestMapping = Objects.requireNonNull(annoAttrs).getBoolean(SwaggerApiConstant.enableRequestMapping);
        SwaggerApiConstant.enable.put(SwaggerApiConstant.enableCheckParams,enableCheckParams);
        SwaggerApiConstant.enable.put(SwaggerApiConstant.enableRequestMapping,enableRequestMapping);

        //自定义的包扫描器
        ApiClassPathScanHandle scanHandle = new ApiClassPathScanHandle(beanDefinitionRegistry,true);

        if(resourceLoader != null){
            scanHandle.setResourceLoader(resourceLoader);
        }
        //这里实现的是根据名称来注入
        scanHandle.setBeanNameGenerator(new ApiBeanNameGenerator());
        //扫描指定路径下的接口
        scanHandle.doScan(basePackages);

    }

}